package com.atguigu.gmall.common.config.interceptor.component;

import com.atguigu.gmall.cart.entity.UserAuth;
import com.atguigu.gmall.common.consts.RedisConst;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.common.util.ReqUtil;
import com.atguigu.gmall.model.user.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author:lyd
 **/
@Component
public class UserAuthComponent {
    @Autowired
    StringRedisTemplate redisTemplate;

    public UserAuth getUserAuth() {
        HttpServletRequest request = ReqUtil.getOldRequest();
        if (request == null) {
            return null;
        }
        //封装返回的值
        UserAuth userAuth = new UserAuth();
        //1、从cookie中获取token和userTempId
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("token".equalsIgnoreCase(name)) {
                    String tokenValue = cookie.getValue();
                    if (StringUtils.hasText(tokenValue)) {
                        String userJson = redisTemplate.opsForValue().get(RedisConst.LOGIN_USER + tokenValue);
                        UserInfo userInfo = JsonUtil.strToObj(userJson, UserInfo.class);
                        userAuth.setUserId(userInfo.getId());
                    }
                }
                //未登录，临时id
                if ("userTempId".equalsIgnoreCase(name)) {
                    String userTempIdValue = cookie.getValue();
                    userAuth.setUserTempId(userTempIdValue);
                }
            }
        }
        //2、从请求头中中获取token和userTempId
        if (userAuth.getUserId() == null && userAuth.getUserTempId() == null) {
            String token = request.getHeader("token");
            if (StringUtils.hasText(token)) {
                String userJson = redisTemplate.opsForValue().get(RedisConst.LOGIN_USER + token);
                UserInfo userInfo = JsonUtil.strToObj(userJson, UserInfo.class);
                userAuth.setUserId(userInfo.getId());
            }
            String userTempId = request.getHeader("userTempId");
            if (StringUtils.hasText(userTempId)) {
                userAuth.setUserTempId(userTempId);
            }
        }
        return userAuth;
    }
}
